/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lczyfz.wisdom.modules.platform.service;

import com.lczyfz.wisdom.common.persistence.Page;
import com.lczyfz.wisdom.common.service.CrudService;
import com.lczyfz.wisdom.common.utils.ResponseCode;
import com.lczyfz.wisdom.common.utils.ServerResponse;
import com.lczyfz.wisdom.modules.platform.dao.SysRegionDao;
import com.lczyfz.wisdom.modules.platform.entity.SysRegion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 省市区地址Service
 * @author zkh
 * @version 2019-11-11
 */
@Service
@Transactional(readOnly = true)
public class SysRegionService extends CrudService<SysRegionDao,SysRegion> {

	@Autowired
	private SysRegionDao sysRegionDao;

	public SysRegion get(String id) {
		return super.get(id);
	}
	
	public List<SysRegion> findList(SysRegion sysRegion) {
		return super.findList(sysRegion);
	}
	
	public Page<SysRegion> findPage(Page<SysRegion> page, SysRegion sysRegion) {
		return super.findPage(page, sysRegion);
	}
	
	@Transactional(readOnly = false)
	public void save(SysRegion sysRegion) {
		super.save(sysRegion);
	}
	
	@Transactional(readOnly = false)
	public void delete(SysRegion sysRegion) {
		super.delete(sysRegion);
	}

	//获取省市区树形结构
	public ServerResponse<SysRegion> getAll() {
		List<SysRegion> newList = new ArrayList<SysRegion>();
		ServerResponse<SysRegion> ServerResponse = new ServerResponse<SysRegion>(0,"获取省市区树形结构成功");
		try {
			List<SysRegion> list = sysRegionDao.getAll();
			newList = parseSysRegionTree(list);
			if (newList.size() > 0){
				ServerResponse.setDataList(newList);
			}
		}catch (Exception e){
			e.printStackTrace();
			return  new ServerResponse<SysRegion>(-10001,"获取省市区树形结构失败");
		}
		return ServerResponse;
	}

	public  List<SysRegion> parseSysRegionTree(List<SysRegion> list){
		List<SysRegion> result = new ArrayList<SysRegion>();
		// 1、获取第一级节点
		for (SysRegion sysRegion : list) {
			if(null == sysRegion.getParent()) {
				result.add(sysRegion);
			}
		}
		// 2、递归获取子节点
		for (SysRegion parent : result) {
			parent = recursiveTree(parent, list);
		}
		return result;
	}

	public  SysRegion recursiveTree(SysRegion parent, List<SysRegion> list) {
		String parentId = parent.getId();
		for (SysRegion sysRegionDetail : list) {
			String fid = sysRegionDetail.getParent();
			if (parentId.equals(fid)) {
				sysRegionDetail = recursiveTree(sysRegionDetail, list);
				parent.getChildList().add(sysRegionDetail);
			}
		}
		return parent;
	}
	
}